/**
 * Copyright (C) @2014 Webank Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.webank.framework.integration.dao.dialect;

import cn.webank.framework.dto.PageInfo;

public class OracleDialect implements Dialect {

	@Override
	public String getCountSql(String sql) {
		return "select count(1) from ( " + sql + " ) ";
	}

	@Override
	public String getLimitSql(String sql, PageInfo pageInfo) {
		int offset = (pageInfo.getCurrentPage() - 1) * pageInfo.getPageSize();
		int limit = pageInfo.getCurrentPage() * pageInfo.getPageSize();
		String querySelect = sql.trim();
		boolean isForUpdate = false;
		if (querySelect.toLowerCase().endsWith(" for update")) {
			querySelect = querySelect.substring(0, querySelect.length() - 11);
			isForUpdate = true;
		}

		StringBuffer pageSql = new StringBuffer(querySelect.length() + 100);
		pageSql.append("select * from ( select row_.*, rownum rownum_ from ( ");
		pageSql.append(querySelect);
		pageSql.append(" ) row_ ) where rownum_ > " + offset
				+ " and rownum_ <= " + (offset + limit));
		if (isForUpdate) {
			pageSql.append(" for update");
		}
		return pageSql.toString();

	}

}
